package com.yilong.springcloudalibabanacos.sys.advice;


import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.yilong.springcloudalibabanacos.sys.entity.ResponseVO;
import com.yilong.springcloudalibabanacos.sys.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.List;

/**
 * @author SOS
 * 如果继承了swagger需要将包扫描修改下路径
 */
@RestControllerAdvice(basePackages = "com.yilong.springcloudalibabanacos.sys.controller")
@Slf4j
public class ResultAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return methodParameter.getDeclaringClass().isAnnotationPresent(RestController.class);
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (o instanceof String) {
            return JsonUtil.toStr(ResponseVO.ok(o));
        }
        if (o instanceof List) {
            return ResponseVO.ok(o, ((List<?>) o).size());
        }
        return ResponseVO.ok(o);
    }

    @ExceptionHandler
    public Object handleException(Exception e) {
        log.error("发生异常，原因：{}", e.getMessage());
        return ResponseVO.error();
    }

    @ExceptionHandler
    public Object handleException(MybatisPlusException e) {
        log.error("发生异常，原因：{}", e.getMessage());
        return ResponseVO.error(e.getMessage());
    }
}
